#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;

//临界资源
int tickets = 100;
pthread_mutex_t mutex;

void *getTickets(void *args)
{
    string name = (char *)(args);
    while (1)
    {
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            usleep(1000);
            cout << name << " 抢到票" << tickets-- << endl;
            pthread_mutex_unlock(&mutex);
            usleep(123);
        }
        else
        {
            cout << name << " 停止抢票，因为无票。" << endl;
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t tid[4];
    pthread_mutex_init(&mutex, nullptr);
    string pthreadName = "thread ";

    for (int i = 0; i < 4; i++)
    {
        pthreadName += i + '0';
        pthread_create(&tid[i], nullptr, getTickets, (void *)pthreadName.c_str());
        usleep(1000);
        pthreadName.pop_back();
    }

    for (int i = 0; i < 4; i++)
    {
        pthread_join(tid[i], nullptr);
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}